package com.resume.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.resume.bean.PageBean;
import com.resume.domain.City;
import com.resume.domain.CityQuery;
import com.resume.mapper.CityMapper;
import com.resume.service.CityService;
import com.resume.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 梁云亮
 * @Date: 2021/7/19 20:21
 * @Describe:
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {

    @Resource
    private RedisUtil<List<City>> redisUtil;

    @Override
    public List<City> listCity(CityQuery cityQuery) {
        List<City> cityList;
        if (redisUtil.hHasKey("hash_city",cityQuery.getProvinceId() + "")) {
//          如果缓存中存在，直接从缓存中取
            cityList = redisUtil.hget("hash_city",cityQuery.getProvinceId() + "");
        } else {
            //如果不存在
            QueryWrapper<City> queryWrapper = new QueryWrapper<>();
            if (cityQuery != null) {
                if (cityQuery.getName() != null) {
                    queryWrapper.eq("name", cityQuery.getName());
                }
                if (cityQuery.getStatus() != null) {
                    queryWrapper.eq("status", cityQuery.getStatus());
                }
                if (cityQuery.getProvinceId() != null) {
                    queryWrapper.eq("province_id", cityQuery.getProvinceId());
                }
            }
            cityList = baseMapper.selectList(queryWrapper);
            //将查询出来的数据放到缓存中
            redisUtil.hset("hash_city", cityQuery.getProvinceId() + "",cityList);
        }

        return cityList;
    }

    @Override
    public PageBean<City> pageCity(CityQuery cityQuery) {
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        if (cityQuery != null) {
            if (cityQuery.getName() != null) {
                queryWrapper.eq("name", cityQuery.getName());
            }
            if (cityQuery.getStatus() != null) {
                queryWrapper.eq("status", cityQuery.getStatus());
            }
            if (cityQuery.getProvinceId() != null) {
                queryWrapper.eq("province_id", cityQuery.getProvinceId());
            }
        }
        IPage<City> page = new Page<>(cityQuery.getPageNum(), cityQuery.getPageSize());


        IPage<City> cityPage = baseMapper.selectPage(page, queryWrapper);

        PageBean<City> res = PageBean.init(cityPage);

        return res;
    }


}
